package com.zhangxiaofanfan.hotcode.second;

/**
 * TODO
 *
 * @author zhangxiaofanfan
 * @date 2024-06-18 22:48:00
 */
public class HotCode047 {
    public static void main(String[] args) {
        int[] preorder = {3,9,20,15,7};
        int[] inorder = {9,3,15,20,7};
        HotCode047 hotCode = new HotCode047();
        TreeNode tree = hotCode.buildTree(preorder, inorder);
        System.out.println("end");
    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || preorder.length == 0) {
            return null;
        }
        return buildTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1);
    }

    public TreeNode buildTree(int[] preorder, int preLeft, int preRight, int[] inorder, int inLeft, int inRight) {
        if (preLeft > preRight) {
            return null;
        }
        if (preLeft == preRight) {
            return new TreeNode(preorder[preLeft]);
        }
        int inTargetIndex = -1;
        for (int i = inLeft; i <= inRight; i++) {
            if (inorder[i] == preorder[preLeft]) {
                inTargetIndex = i;
                break;
            }
        }
        if (inTargetIndex == -1) {
            throw new RuntimeException("不能构建出树对象");
        }
        TreeNode father = new TreeNode(preorder[preLeft]);

        father.left = buildTree(preorder, preLeft + 1, preLeft + inTargetIndex - inLeft, inorder, inLeft, inTargetIndex - 1);
        father.right = buildTree(preorder, preLeft + inTargetIndex - inLeft + 1, preRight, inorder, inTargetIndex + 1, inRight);

        return father;
    }

    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
}
